package com.xsg.printer.core.toolkit;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.sun.org.slf4j.internal.Logger;
import com.sun.org.slf4j.internal.LoggerFactory;
import com.xsg.printer.core.enums.VoucherConstants;
import org.apache.commons.lang.StringUtils;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @Classname ZxingQRCodeUtil
 * @Description Zxing二维码生成工具
 * @Date 2019-08-29 17:53
 */
public class QRCodeUtil {
    private static final int QRCOLOR = 0xFF000000; // 默认是黑色

    private static final int BGWHITE = 0xFFFFFFFF; // 背景颜色

    /**
     * 用于设置QR二维码参数
     */
    private static Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>() {
        {
            // 设置QR二维码的纠错级别（H为最高级别）具体级别信息
            put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
            put(EncodeHintType.CHARACTER_SET, "UTF-8");
            put(EncodeHintType.MARGIN, 0);
        }
    };

    /**
     * 二维码
     * @param qrData
     * @param width
     * @param height
     * @return
     */
    public static String drawQRCode (String qrData, int width, int height) {
        if (StringUtils.isEmpty(qrData)) {
            return null;
        }
        File file = new File(PathUtil.getRandomPngPath());
        try {
            // 开始生成二维码
            BitMatrix bitMatrix = new MultiFormatWriter().encode(qrData, BarcodeFormat.QR_CODE, width, height, hints);
            BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            // 开始利用二维码数据创建Bitmap图片，分别设为黑（0xFFFFFFFF）白（0xFF000000）两色
            for (int x = 0; x < width; x++) {
                for (int y = 0; y < height; y++) {
                    image.setRGB(x, y, bitMatrix.get(x, y) ? QRCOLOR : BGWHITE);
                }
            }
            image.flush();
            ImageIO.write(image, "png", file);
        } catch (WriterException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file.getPath();
    }
}
